package com.xiaojian.pick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaojian.pick.entity.UserAddress;
import com.xiaojian.pick.mapper.UserAddressMapper;
import com.xiaojian.pick.service.UserAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author whycode
 * @title: UserAddress
 * @projectName campus-secondary-market-app---sys
 * @description: TODO
 * @date 2022/2/208:07
 */

@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {


    @Override
    public boolean saveOrUpdate(UserAddress entity) {
        if(entity.getIsDefault() == 1){
            this.cleanDefault(entity.getUserId());
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional
    public boolean updateDefaultById(Integer id, Integer userId, Short status) {

        this.cleanDefault(userId);
        if(status != null && status == 1){
            getBaseMapper().update(new UserAddress(),
                    new UpdateWrapper<UserAddress>()
                            .set("is_default", 1)
                            .eq("id", id));
        }
        return true;
    }

    private void cleanDefault(Integer userId){
        getBaseMapper().update(new UserAddress(),
                new UpdateWrapper<UserAddress>().set("is_default", 0)
                        .eq("user_id", userId)
                        .eq("is_default", 1));
    }

    @Override
    public boolean deleteById(Integer id) {
        getBaseMapper().update(new UserAddress(),
                new UpdateWrapper<UserAddress>()
                        .set("status", -1)
                        .eq("id", id));
        return true;
    }
}
